import re
import yaml
import socket
from ActiveUser import ActiveUser
#from TestCookie import test_cookie
from GetDataFromAuthServer import test_cookie
from msg import *
from SendToNeighbours import send_message_to_neighbors
import globals
from GetDataFromAuthServer import get_user_metadata

def check_in (mp, userName, cookie, statusToUpload, available):

    #isValid = test_cookie(userName, cookie)
    #if isValid:

    # Create a new user entry in the Active user list

    if userName == '' :
        return False

    data = get_user_metadata(userName)
    if data == "INVALID" :
        return False

    metadata= data.split(',')

    firstName = metadata[0]
    lastName = metadata[1]
    userGroup = metadata[2]

    # userGroupsList = get_user_groups(userName)
    f = ActiveUser(userName, available, statusToUpload, firstName, lastName, userGroup)
    try :
        globals.globalActiveUserListLock.acquire()
        globals.globalActiveUserList[userName] = f
    finally :
        globals.globalActiveUserListLock.release()

    # print globalActiveUserList
    #send this message to the neighbouring nodes
    #data = mp.thisName + "^%" + userName + "^%" + available + "^%" + statusToUpload
    data = yaml.dump(f)
    msg = Message(mp.thisName, None, None, data, 'check_in_nodes', mp.thisName)
    #msg.setBroadcastSource(mp.thisName)
    #print " msg.broadcastSource is : " + msg.broadcastSource
    #msg = Message(None, None, None, data, 'check_in_nodes')
    send_message_to_neighbors (mp, msg)
    # print "current data and time is : " + datetime.now()
    return True
    #else :
    #return False
